package com.yang.thread;

/**
 * 基础线程示例 - 演示创建线程的两种方式
 * 1. 继承Thread类
 * 2. 实现Runnable接口
 */
public class BasicThreadExample {
    
    public static void main(String[] args) {
        System.out.println("=== 基础线程示例 ===");
        
        // 方式1：继承Thread类
        MyThread thread1 = new MyThread("线程1");
        MyThread thread2 = new MyThread("线程2");
        
        // 方式2：实现Runnable接口
        Thread thread3 = new Thread(new MyRunnable("任务1"));
        Thread thread4 = new Thread(new MyRunnable("任务2"));
        
        // 方式3：使用Lambda表达式（Java 8+）
        Thread thread5 = new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                System.out.println("Lambda线程 - 计数: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        
        // 启动所有线程
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        
        // 等待所有线程完成
        try {
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
            thread5.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        System.out.println("所有线程执行完毕！");
    }
}

/**
 * 方式1：继承Thread类
 */
class MyThread extends Thread {
    private String threadName;
    
    public MyThread(String name) {
        this.threadName = name;
    }
    
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(threadName + " - 计数: " + i + 
                             " [线程ID: " + Thread.currentThread().getId() + "]");
            try {
                Thread.sleep(1000); // 暂停1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println(threadName + " 被中断");
                return;
            }
        }
        System.out.println(threadName + " 执行完毕");
    }
}

/**
 * 方式2：实现Runnable接口
 */
class MyRunnable implements Runnable {
    private String taskName;
    
    public MyRunnable(String name) {
        this.taskName = name;
    }
    
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(taskName + " - 计数: " + i + 
                             " [线程ID: " + Thread.currentThread().getId() + "]");
            try {
                Thread.sleep(1500); // 暂停1.5秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println(taskName + " 被中断");
                return;
            }
        }
        System.out.println(taskName + " 执行完毕");
    }
}
